package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.*;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.ParamErrorException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!passwordMd5.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (UserConstant.STATUS_DISABLE.equals(employee.getStatus())) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        /**
         * 空值检验: username name phone sex phone idNumber
         * 长度校验: phone必须是11位、idNumber必须是18位
         * 重复校验: username、phone、idNumber
         * todo 选做:[合法性校验: 手机号和身份证号必须符合大陆要求、sex必须时0或1]
         */
        String username = employeeDTO.getUsername();
        String name = employeeDTO.getName();
        String phone = employeeDTO.getPhone();
        String sex = employeeDTO.getSex();
        String idNumber = employeeDTO.getIdNumber();
        // 空值判断
        if (username == null || name == null || phone == null || sex == null || idNumber == null) {
            // 抛出空值异常
            throw new ParamErrorException(MessageConstant.NEW_EMPLOYEE_PARAM_NULL);
        }
        // 长度校验
        if (phone.length() != UserConstant.PHONE_LENGTH || idNumber.length() != UserConstant.ID_NUMBER_LENGTH) {
            throw new ParamErrorException(MessageConstant.PHONE_OR_ID_NUMBER_LENGTH_ERROR);
        }
        // 重复检验 todo 需要查数据库

        log.info("新增员工: {}", employeeDTO);
        Employee employee = new Employee();

        // 对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        // 设置账号的状态: 默认正常状态(1)
        employee.setStatus(UserConstant.STATUS_ENABLE);
        // 设置账号的默认密码
        String passwordMD5 = DigestUtils.md5DigestAsHex(UserConstant.USER_DEFAULT_PASSWORD.getBytes());
        employee.setPassword(passwordMD5);

        // 执行数据库插入操作
        employeeMapper.insert(employee);
    }

    /**
     * 分页条件查询员工
     *
     * @param pageQuery [分页]与[条件]参数
     * @return PageResult 分页结果
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO pageQuery) {
        String name = pageQuery.getName();
        int pageNum = pageQuery.getPage();
        int pageSize = pageQuery.getPageSize();
        // 校验分页查询的参数
        if (pageNum == 0) {
            pageNum = UserConstant.PAGE_NUM_QUERY_DEFAULT;
        }
        if (pageSize == 0) {
            pageSize = UserConstant.PAGE_SIZE_QUERY_DEFAULT;
        }

        // 分页查询
        PageHelper.startPage(pageNum, pageSize);
        Page<Employee> page = employeeMapper.pageQuery(name);

        long total = page.getTotal();
        List<Employee> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 修改员工状态
     * @param id 员工id
     * @param status 员工状态
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        // 校验状态参数的合法性
        checkAccountExist(id);
        checkStatus(status);
        checkUserAllowedBeOperated(id);
        employeeMapper.update(new Employee(id, status));
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getEmployeeById(Long id) {
        checkAccountExist(id);
        return employeeMapper.getByUserId(id);
    }

    /**
     * 修改员工信息
     * @param employee
     */
    @Override
    public void updateEmployee(EmployeeDTO employee) {
        // 合法性校验
        // todo 更新操作参数校验与添加操作不一样
        checkUserAllowedBeOperated(employee.getId());

        // 属性拷贝
        Employee employeeDb = new Employee();
        BeanUtils.copyProperties(employee, employeeDb);

        // 更新员工信息
        employeeMapper.update(employeeDb);
    }

    /**
     * 校验账号是否存在
     */
    public void checkAccountExist(Long userId) {
        Employee employee = employeeMapper.getByUserId(userId);
        if (Objects.isNull(employee)) {
            throw new ParamErrorException("用户id不存在");
        }
    }

    /**
     * 校验员工参数的合法性
     * @param employee
     */
    public void checkAccount(EmployeeDTO employee) {
        if (!UserConstant.validateSexLegal(employee.getSex())) {
            throw new ParamErrorException("性别参数不合法");
        }
        if (employee.getIdNumber().isEmpty()) {
            throw new ParamErrorException("身份证号码不能为空");
        }
        if (employee.getPhone().isEmpty()) {
            throw new ParamErrorException("手机号码不能为空");
        }
        if (Objects.nonNull(employeeMapper.getByUsername(employee.getUsername()))) {
            throw new ParamErrorException("账号已存在");
        }
    }

    /**
     * 校验状态参数的合法性
     * @param status
     */
    public void checkStatus(Integer status) {
        if (!UserConstant.validateStatusLegal(status)) {
            throw new ParamErrorException("状态参数不合法");
        }
    }

    /**
     * 校验用户是否允许被操作
     * @param id
     */
    public void checkUserAllowedBeOperated(Long id) {
        // 判断当前登录用户是否是管理员
        if (Objects.nonNull(id) && id.equals("1")) {
            throw new ParamErrorException("不允许对管理员进行操作");
        }
    }


}
